var currentThread;
var messagesCache = {};
var likesCache = {};
var mostRecentMessageNumber = 0;
var mostRecentLikedNumber = 0;
var previouslyViewedClassID = -1;

// called when you first go into a class
function loadMessages()
{
	// if this isn't the most recently viewed class, we need to reset the content
	if(previouslyViewedClassID != currentClass.uniqueCourseNumber)
	{
		messagesCache = {};
		likesCache = {};
		mostRecentMessageNumber = 0;
		mostRecentLikedNumber = 0;
		previouslyViewedClassID = currentClass.uniqueCourseNumber;
		
		// get the HTML DOM ready to be reused
		$('#threadList').empty();
		$('#messageList').empty();
	}
	
	updateMessages();
}

// updates messages for the current class
function updateMessages(i)
{
	$.getJSON('php/messages.php',
		{
			action:'list_new_messages',
			uniqueCourseNumber: currentClass.uniqueCourseNumber,
			mostRecentMessageNumber: mostRecentMessageNumber
		},
		function(response)
		{
			// first, update the HTML DOM
			var threadList = $('#threadList');
			for (var message_index in response)
			{
				var author = response[message_index].author;
				var time = response[message_index].postTime;
				var message = response[message_index].message;
				var thread_num = response[message_index].thread + ''; //this will be a string
				var message_num = response[message_index].uniqueMessageNumber;
				
				// check to see if author is empty
				author = author == '' ? 'unknown' : author;
				
				// if there is a new thread, update the thread list
				if((messagesCache[thread_num]) == undefined)	// this means there's a new thread
				{
					// to store thread messages locally and so we know we've seen this thread the next
					// time we check for a new thread with this same thread number
					messagesCache[thread_num]= new Array();
					
					// display a new list item for the new thread
					$('<li class="arrow" id="' + thread_num + '">'
					
					+ '<div class="message">' + message + '</div>'
					
					+ '<span class="stats">'
					+ 'By ' + author + ', '
					+ '<span class="numResponses">0</span> Responses, '
					+ '<span class="numLikes">0</span> Total Likes'
					+ '</span>'
					
					+ '</li>').prependTo(threadList).bind('mouseup',showMessageListView);
					
					// update the numLikes for this new thread in case some likes already came in for it
					if(likesCache[thread_num])
					{
						var threadListItem = $('li[id="' + thread_num + '"]',$('#threadList'));
						var numLikesSpan = $('span[class="numLikes"]',threadListItem);
						numLikesSpan.text(likesCache[thread_num].likeCount);
					}
				}
				else
				{
					// if the message is part of an existing thread, increment the response count
					var threadListItem = $('li[id="' + thread_num + '"]',$('#threadList'));
					var numResponsesSpan = $('span[class="numResponses"]',threadListItem);
					var newCount = parseInt(numResponsesSpan.text()) + 1;
					numResponsesSpan.text(newCount);
				}
				
				// if a thread is being viewed, update the messages list for that thread
				if(currentThread == thread_num)
				{
				
					var likeButtonSpan = '<span class="likeButton">Like</span>';
					if(likesCache[currentThread] && likesCache[currentThread][message_num] && likesCache[thread_num][message_num].userLiked)
						likeButtonSpan = '<span class="disabledLikeButton">Liked</span>';

					// update the list of messages in that thread
					var newMessageListItem = $('<li id="' + message_num + '">'
					
					+ '<div class="message">' + message+ '</div>'
					
					+ '<span class="stats">'
					+ 'By ' + author + ', '
					+ '<span class="numLikes">0</span> Likes'
					+ '</span>'
					
					+ likeButtonSpan
					
					+ '</li>');

					
					$('#messageList').append(newMessageListItem);
					
					$('.likeButton').bind('mouseup', likeMessage);
				}
			}
			
			// next, cache the new messages
			for (var message_index in response)
			{
				var thread_num = response[message_index].thread + '';	// this will be a string
				
				messagesCache[thread_num].push(response[message_index]);
				
				// update the most recent message number
				mostRecentMessageNumber = response[message_index].uniqueMessageNumber;
			}
		}
	);
	$.getJSON('php/messages.php',
		{
			action: 'list_new_likes',
			uniqueCourseNumber: currentClass.uniqueCourseNumber,
			mostRecentLikedNumber: mostRecentLikedNumber
		},
		function(response)
		{
			// update likesCache
			for(like_index in response)
			{
				var thread_num = response[like_index].uniqueThreadNumber + '';
				var message_num = response[like_index].uniqueMessageNumber + '';
				
				if (likesCache[thread_num] == undefined)
				{
					likesCache[thread_num] = {};
					likesCache[thread_num].likeCount = 0;
				}
				
				if (likesCache[thread_num][message_num] == undefined)
				{
					likesCache[thread_num][message_num] = new Array();
					likesCache[thread_num][message_num].likeCount = 0;
					likesCache[thread_num][message_num].userLiked = false;
				}
				
				// cache the like
				likesCache[thread_num][message_num].push(response[like_index]);
				
				// increment the like counts
				likesCache[thread_num].likeCount = likesCache[thread_num].likeCount + 1;
				likesCache[thread_num][message_num].likeCount = likesCache[thread_num][message_num].likeCount + 1;
				
				// set the user liked if the user liked the message
				if(response[like_index].author == userName)
					likesCache[thread_num][message_num].userLiked = true;
				
				// update the most recent liked number
				mostRecentLikedNumber = response[like_index].uniqueLikedNumber;
			}
			
			// update the DOM
			for(like_index in response)
			{
				var thread_num = response[like_index].uniqueThreadNumber + '';
				var message_num = response[like_index].uniqueMessageNumber + '';
				
				// update the total likes count in the thread list
				var threadListItem = $('li[id="' + thread_num + '"]',$('#threadList'));
				var numLikesSpan = $('span[class="numLikes"]',threadListItem);
				numLikesSpan.text(likesCache[thread_num].likeCount);
				
				// if a thread is being viewed, update the numLikes for messages in that thread
				if(currentThread == thread_num)
				{
					var messageListItem = $('li[id="' + message_num + '"]',$('#messageList'));
					numLikesSpan = $('span[class="numLikes"]',messageListItem);
					numLikesSpan.text(likesCache[thread_num][message_num].likeCount);
				}
			}
		}
	);
}

function showMessageListView(event)
{
	// remember the thread the user selected
	currentThread = $(this).attr('id');
	
	// display the messages for the thread
	var messageList = $('#messageList').empty();	// erase any existing messages on the page
	var threadMessages = messagesCache[currentThread];
	for (var message_index in threadMessages)
	{
		var author = threadMessages[message_index].author;
		var time = threadMessages[message_index].postTime;
		var message = threadMessages[message_index].message;
		var message_num = threadMessages[message_index].uniqueMessageNumber + '';
		
		var likeButtonSpan = '<span class="likeButton">Like</span>';
		if(likesCache[currentThread] && likesCache[currentThread][message_num] && likesCache[currentThread][message_num].userLiked)
			likeButtonSpan = '<span class="likedButton">Liked</span>';
		
		var num_likes = 0;
		if(likesCache[currentThread] && likesCache[currentThread][message_num])
			num_likes = likesCache[currentThread][message_num].likeCount;
		
		// check to see if author is empty
		author = author == '' ? 'unknown' : author;

		$('<li id="' + message_num + '">'
		
		+ '<div class="message">' + message+ '</div>'
		
		+ '<span class="stats">'
		+ 'By ' + author + ', '
		+ '<span class="numLikes">' + num_likes + '</span> Likes'
		+ '</span>'
		
		+ likeButtonSpan
		
		+ '</li>').appendTo(messageList);
	}
	
	$('.likeButton').bind('mouseup', likeMessage);
	
	jQT.goTo('#messageListView', 'slide');
}

// submit reply
function submitReply(event)
{
	$.getJSON('php/messages.php',
		{
			action:'submit_message',
			thread: currentThread,
			message: $('#response_text').val(),
			uniqueCourseNumber: currentClass.uniqueCourseNumber
		},
		function(response){
			if (response.success =='false') {
				console.log('Unable to submit message.');
			}
		}
	);
	
	jQT.goBack(1);
}

// post new thread
function submitNewThread(event)
{
	$.getJSON('php/messages.php',
		{
			action:'submit_message',
			thread: 'null',
			message: $('#newThreadText').val(),
			uniqueCourseNumber: currentClass.uniqueCourseNumber
		},
		function(response){
			if (response.success =='false') {
				console.log('Unable to submit message.');
			}
		}
	);
	
	jQT.goBack(1);
}

// like a message in response to mouseup on a "Like" text link
function likeMessage(event)
{
	var parentListItem = $(this).parents('li');
	var message_num = parentListItem.attr('id');
	
	$(this).text('Liked').unbind();
	
	$.getJSON('php/messages.php',
		{
			action: 'like_message',
			uniqueCourseNumber: currentClass.uniqueCourseNumber,
			uniqueMessageNumber: message_num
		},
		function(response)
		{
			if(response.success == 'true')
			{
				//console.log('Liked message.');
			}
			else
			{
				console.error('Failed to like message.');
			}
		}
	);
}